import { Controller, Post, Body, Res } from '@nestjs/common';
import { AppService } from './app.service';
import { Response } from 'express';
import { join } from 'path';
import { promises as fsPromises } from 'fs';

@Controller('api')
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Post('image-recognition')
  async recognizeImage(@Body() body: { image: string }) {
    return this.appService.recognizeImage(body.image);
  }

  @Post('result')
  async showResult(
    @Body() body: { result: string; image: string },
    @Res() res: Response,
  ) {
    try {
      // 读取result.html模板
      const templatePath = join(process.cwd(), 'public', 'result.html');
      let html = await fsPromises.readFile(templatePath, 'utf8');

      // 注入数据
      html = html.replace(
        '</head>',
        `<script>
          window.RESULT_DATA = {
            result: ${JSON.stringify(body.result)},
            image: ${JSON.stringify(body.image)}
          };
        </script>
        </head>`,
      );

      // 发送响应
      res.send(html);
    } catch (error) {
      console.error('处理结果页面时出错:', error);
      res.status(500).send('处理结果时发生错误');
    }
  }
}
